import random

from bs4 import BeautifulSoup
import requests
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from com.demo1.redis_demo.redis_client import RedisHelper
from apscheduler.schedulers.blocking import BlockingScheduler


def check_sensitive_msg(id, msg):
    cache_key = f"sensitive_msg_{id}"
    id_msg = RedisHelper().get_by_key(cache_key)
    if id_msg:
        return False
    # 敏感词需要配置，这里简单处理
    sensitive_words = {"敏感词1", "敏感词2", "敏感词3"}
    for word in sensitive_words:
        if word in msg:
            # 配置间隔时间，同一个信息短时间内部重复触发
            RedisHelper().set_by_key(cache_key, 1, 24 * 60 * 60)
            return True
    return False


def get_page(url):
    # 发现不加 header 获取内容是空；先尝试加 User-Agent；
    # 如果还是空，那就需要加更多的 header
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/'
                      '537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36',
    }

    r = requests.get(url, headers=headers)
    html = r.text
    soup = BeautifulSoup(html, "html.parser")

    all_menu_html = soup.findAll("div", class_="extra text")
    # 从左侧菜单 html 内容中获取所有菜单信息，并且按照（url，展示问诊）的格式返回
    all_msg = []
    for menu_html in all_menu_html:
        for a in menu_html.find_all("a"):
            # print(a.string)
            all_msg.append(a.string)
    return all_msg


def send_email():
    # 配置发件人、收件人、SMTP服务器等信息
    global server
    subject = "告警邮件"
    message = "发现舆情告警邮件。"
    from_addr = "123@qq.com"
    to_addr = "123g"
    smtp_server = "smtp.qq.com"  # SMTP服务器地址
    smtp_port = 465  # SSL端口通常是465
    username = "1234@qq.com"  # 登录SMTP服务器的用户名
    password = "sadfghzxcvbn4567"  # 登录SMTP服务器的密码
    # 创建一个带附件的实例
    msg = MIMEMultipart()

    # 设置邮件头部信息
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Subject'] = subject

    # 邮件正文内容
    msg.attach(MIMEText(message, 'plain'))

    try:
        # 连接到SMTP服务器
        server = smtplib.SMTP_SSL(smtp_server, smtp_port)
        server.login(username, password)

        # 发送邮件
        server.sendmail(from_addr, to_addr, msg.as_string())
        print("邮件发送成功")
    except Exception as e:
        print(f"邮件发送失败: {e}")
    finally:
        # 关闭服务器连接
        server.quit()


def do_sensitive():
    all_msg = get_page("https://www.oschina.net/?type=ajax&widget=section_comment_update")
    for msg in all_msg:
        id = random.randint(1, 100000)
        if check_sensitive_msg(id, msg):
            send_email()


# scheduler = BlockingScheduler()
# # 每天早上9点开始，每20分钟执行一次
# # 开始结束时间需要配置，支持指定日期，指定开始时间，指定结束时间
# scheduler.add_job(do_sensitive, 'interval', minutes=20, start_date='09:00', end_date='16:59', timezone='Asia/Shanghai')
# scheduler.start()
# get_page("https://www.oschina.net/?type=ajax&widget=section_comment_update")
# send_email()
do_sensitive()
